const mysql = require('mysql')
let client = undefined;

const query = (sql, cb)=>{
    console.log(`query = ${sql}`);
    client.getConnection((err, connection)=> {
        if (err) {
            console.log(`connection mysql err = ${err}`);
            cb(err);
            throw err;
        } else {
            connection.query(sql, (connerr, result, fileds) => {
                if (connerr) {
                    console.log(`query err = ${connerr}`);
                    cb(connerr);
                } else {
                    cb(null, result);
                }
                connection.release();
            });
        }
    });
};

const insertSql = (table, data) => {
    let keyStr = [];
    let valueStr = [];
    for (const i in data) {
        keyStr.push(i);
        valueStr.push(`'${data[i]}'`);
    }
    let sql = `insert into ${table}(${keyStr.join()}) values(${valueStr.join()}) `;
    return sql;
}
const updateSql = (table, mainKey, data) => {
    let keyStr = [];
    for (const i in data) {
        keyStr.push(`${i}='${data[i]}'`);
    }
    let sql = `update ${table} set ${keyStr.join()} where unique_id='${mainKey}'`;
    return sql;
}

exports.connect = config => {
    client = mysql.createPool(config);
}

exports.checkPalyer = (uniqueID, cb) => {
    // 查看玩家
    let sql = `select * from t_playerinfo where unique_id = '${ uniqueID }'`;
    query(sql, (err, data) => {
        if (err) {
            console.log(`err = ${err}`);
        } 
        console.log(`check player = ${ JSON.stringify(data) }`);
        cb(err, data);
    });
}

exports.insertPalyer = (data) => {
    let sql = insertSql('t_playerinfo', data);
    console.log(`sql = ${sql}`);
    query(sql, (err, res) => {
        if (err) {
            console.log(`insert player info err = ${err}`);
        } else {
            console.log(`info data = ${JSON.stringify(res)}`);
        }
    });
}

exports.updatePlayerInfo = (mainKey, data) => {
    let sql = updateSql('t_playerinfo', mainKey, data);
    query(sql, (err, res) => {
        if (err) {
            console.log(`update player info err = ${err}`);
        } else {
            console.log(`update info data = ${JSON.stringify(res)}`);
        }
    });
}